package com.heima.item.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.item.pojo.Item;
import com.heima.item.pojo.ItemStock;
import com.heima.item.service.IItemService;
import com.heima.item.service.IItemStockService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Redis初始化
 */
@Component
@RequiredArgsConstructor
public class RedisHandler implements InitializingBean {

    private final StringRedisTemplate stringRedisTemplate;
    private final IItemService itemService;
    private final IItemStockService iItemStockService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void afterPropertiesSet() throws Exception {
        //初始化缓存
        //1.查询商品的全部信息（基本上是热点）
        List<Item> itemList = itemService.list();
        //2.放入缓存
        for (Item item : itemList) {
            //2.1 item->JSON
            String json = MAPPER.writeValueAsString(item);
            //2.存入Redis
            stringRedisTemplate.opsForValue().set("item:id:" + item.getId(), json);
        }

        //3.查询库存的全部信息（基本上是热点）
        List<ItemStock> stockList = iItemStockService.list();
        //4.放入缓存
        for (ItemStock stock : stockList) {
            //2.1 item->JSON
            String json = MAPPER.writeValueAsString(stock);
            //2.存入Redis
            stringRedisTemplate.opsForValue().set("item:stock:id:" + stock.getId(), json);
        }
    }

    public void saveItem(Item item) {
        String json = null;
        try {
            json = MAPPER.writeValueAsString(item);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        stringRedisTemplate.opsForValue().set("item:id:" + item.getId(), json);
    }

    public void deleteItemById(Long id) {
        stringRedisTemplate.delete("item:id:" + id);
    }



}
